#!/usr/env python

from pydht import DHT
import util
import getopt, sys

host = util.get_IP_Address()
port = 6666
user = ''

bootstrap_host = util.get_IP_Address()
bootstrap_port = 0

def main():
  global host, port, user
  global bootstrap_host,bootstrap_port
  try:
    opts, args = getopt.getopt(sys.argv[1:], 'h:u:p:b:r:',
                               ['host=', 'user=', 'port=', 'bs-port=',
                                'bs-host='])
  except getopt.GetoptError as err:
    exit()

  for o, a in opts:
    if o in ('-h', '--host'):
      host = a
    elif o in ('-p', '--port'):
      port = int(a)
    elif o in ('-u', '--user'):
      user = a
    elif o in ('-b', '--bs-port'):
      bootstrap_port = int(a)
    elif o in ('-r', '--bs-host'):
      bootstrap_host = a

  pk = util.get_private_key(user)
  if not pk:
    print 'generating key for user [%s]' % user
    util.generate_key(user)

  print 'start dht at %s:%d' % (host, port)
  if bootstrap_port == 0:
    dht = DHT(host, port)
  else:
    dht = DHT(host, port, boot_host=bootstrap_host, boot_port=bootstrap_port)

  commands()
  cmd = raw_input().strip()
  while cmd not in ('q', 'quit'):
    if cmd in ('s', 'send'):
      print 'input receiver:'
      receiver = raw_input()
      print 'input message:'
      message = raw_input()
      util.send(dht, user, receiver, message)
      print 'message sent'
    if cmd in ('r', 'recv'):
      msg = util.recv(dht, user)
      if msg:
        for m in msg:
          print m
      else:
        print 'no message received.'
    if cmd in ('h', 'help'):
      commands()

    cmd = raw_input().strip()

def commands():
  print "'s' or 'send' to send message"
  print "'r' or 'recv' to receive message"
  print "'q' or 'quit' to quit"
  print "'h' or 'help' to print this help"

if __name__ == '__main__':
  main()

